#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" user-agent池 """

# 导入标准库
import os
import re
import sys
from argparse import ArgumentParser

import requests



HEADERS = {
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'zh-CN,zh;q=0.9',
    'pragma': 'no-cache',
    'cache-control': 'no-cache',
    'upgrade-insecure-requests': '1',
    'user-agent': "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
}

def input_user_agent():
    UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
    print("user_agent: " + UA)
    return UA

def input_request_url():
    GURL = input("请输入分享的短链接: ").strip()
    if GURL.find('v.douyin.com') < 0:
        return GURL
    res = requests.get(GURL, headers=HEADERS, allow_redirects=False)
    if res.status_code == 302:
        long_url = res.headers['Location']
        HEADERS['Referer'] = long_url
        r = requests.get(long_url)
        number = re.findall(r'share/user/(\d+)', long_url)
        _id = number[0]
    URL = "https://www.amemv.com/web/api/v2/aweme/post/?user_id=" + _id + "&sec_uid=&count=999&max_cursor=0"
    if not os.path.exists("data"):
        os.makedirs("data")
    if not os.path.exists("user_id"):
        print("创建预设文件 user_id ...")
        open("user_id", "w")
    with open("user_id", "w") as f:
        f.write(_id)
    return URL


def get_id_from_cmd(cmd_args):
    '''
    从命令行获取user_id

    :param cmd_args:    命令行参数
    :return:            user_id
    '''
    args = parse_args(cmd_args)
    if not args:
        return

    if args.user_id:
        _id = args.user_id
        return _id
    return None


def get_id_from_input():
    '''
    从用户输入获取user_id

    :return:    user_id
    '''
    with open("user_id", "r") as f:
        _id = f.read()
    return _id


def is_valid_id(_id):
    '''
    检查用户输入的抖音id是否合法

    :param _id:  user_id
    :return:     bool
    '''
    if not _id:
        return False
    if not re.match('^\\d+$', str(_id).strip()):
        sys.stdout.write("请输入正确格式的抖音id\n")
        return False
    return True


def makedir(name):
    '''
    建立用户名文件夹

    :param name:    username
    :return:        None
    '''
    if not os.path.isdir(name):
        os.mkdir(name)
    else:
        pass


def parse_args(args):
    '''
    解析命令行参数

    :param args:    命令行参数
    :return:        新的parse_args函数
    '''
    parser = ArgumentParser()
    parser.add_argument('--uid', dest='user_id', type=int, help='用户的抖音id')
    return parser.parse_args(args)
